package com.demo.crm.springboot3security.validation;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import com.demo.crm.springboot3security.entity.CustomForm;
import com.demo.crm.springboot3security.entity.FormField;
import com.demo.crm.springboot3security.exception.ValidationException;
import com.fasterxml.jackson.databind.ObjectMapper;

import lombok.RequiredArgsConstructor;

@Component
@RequiredArgsConstructor
public class FormDataValidator {
    
    private final ObjectMapper objectMapper;

    /**
     * 验证表单数据
     */
    public void validate(CustomForm form, Map<String, Object> data) {
        List<String> errors = new ArrayList<>();

        for (FormField field : form.getFields()) {
            Object value = data.get(field.getCode());
            
            // 必填验证
            if (field.isRequired() && (value == null || StringUtils.isEmpty(value.toString()))) {
                errors.add(String.format("字段[%s]不能为空", field.getName()));
                continue;
            }

            if (value != null) {
                // 类型验证
                if (!validateFieldType(field, value)) {
                    errors.add(String.format("字段[%s]类型不正确", field.getName()));
                    continue;
                }

                // 自定义验证规则
                if (StringUtils.hasText(field.getValidation())) {
                    String error = validateCustomRule(field, value);
                    if (error != null) {
                        errors.add(error);
                    }
                }
            }
        }

        if (!errors.isEmpty()) {
            throw new ValidationException(String.join("; ", errors));
        }
    }

    /**
     * 验证字段类型
     */
    private boolean validateFieldType(FormField field, Object value) {
        try {
            switch (field.getType()) {
                case NUMBER:
                    if (value instanceof Number) {
                        return true;
                    }
                    Double.parseDouble(value.toString());
                    return true;
                case DATE:
                case TIME:
                case DATETIME:
                    if (value instanceof LocalDateTime) {
                        return true;
                    }
                    // 这里可以添加日期格式的验证
                    return true;
                case EMAIL:
                    return Pattern.matches("^[A-Za-z0-9+_.-]+@(.+)$", value.toString());
                case PHONE:
                    return Pattern.matches("^\\d{11}$", value.toString());
                case URL:
                    return Pattern.matches("^(http|https)://.*$", value.toString());
                default:
                    return true;
            }
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 验证自定义规则
     */
    private String validateCustomRule(FormField field, Object value) {
        try {
            Map<String, Object> rules = objectMapper.readValue(field.getValidation(), Map.class);
            
            // 最小长度
            if (rules.containsKey("minLength")) {
                int minLength = (Integer) rules.get("minLength");
                if (value.toString().length() < minLength) {
                    return String.format("字段[%s]长度不能小于%d", field.getName(), minLength);
                }
            }

            // 最大长度
            if (rules.containsKey("maxLength")) {
                int maxLength = (Integer) rules.get("maxLength");
                if (value.toString().length() > maxLength) {
                    return String.format("字段[%s]长度不能大于%d", field.getName(), maxLength);
                }
            }

            // 正则表达式
            if (rules.containsKey("pattern")) {
                String pattern = (String) rules.get("pattern");
                if (!Pattern.matches(pattern, value.toString())) {
                    return String.format("字段[%s]格式不正确", field.getName());
                }
            }

            // 数值范围
            if (value instanceof Number) {
                double number = ((Number) value).doubleValue();
                
                if (rules.containsKey("min")) {
                    double min = Double.parseDouble(rules.get("min").toString());
                    if (number < min) {
                        return String.format("字段[%s]不能小于%f", field.getName(), min);
                    }
                }

                if (rules.containsKey("max")) {
                    double max = Double.parseDouble(rules.get("max").toString());
                    if (number > max) {
                        return String.format("字段[%s]不能大于%f", field.getName(), max);
                    }
                }
            }
        } catch (Exception e) {
            return String.format("字段[%s]验证规则配置错误", field.getName());
        }
        return null;
    }
} 